package ucd.csi.comp30220.fall2011.oteop.traffic.impl;

import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;

import ucd.csi.comp30220.fall2011.oteop.OTEOP;
import ucd.csi.comp30220.fall2011.oteop.traffic.Traffic;
import ucd.csi.comp30220.fall2011.oteop.traffic.TrafficException;
import ucd.csi.comp30220.fall2011.oteop.util.EndPoint;
import ucd.csi.comp30220.fall2011.oteop.util.ServiceFinder;

public class TrafficClient implements Traffic {
	
	private int port;
	private String host;
	
	public TrafficClient(String airportCode, long timeout) throws Exception{
		EndPoint endPoint = ServiceFinder.findService(
	       OTEOP.JMDNS_TYPE_TCP_LOCAL, Traffic.JMDNS_SUB_TYPE, getTraffic(airportCode), timeout);
	    if (endPoint == null)
	        throw new Exception("Failed to get Traffic in " +timeout +"ms");
	    host = endPoint.getHost();
	    port = endPoint.getPort();
	}
	
	static String getTraffic(String airportCode) {
	    return "shannon";
	}

	public void handleFlight(String flightNum) throws TrafficException, IOException {
		Socket s = new Socket(host, port);
		PrintWriter out = new PrintWriter(s.getOutputStream());
		out.println(flightNum);
		out.flush();
		out.close();
		s.close();
	}
}
